package com.wensi.lib_base

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import com.wensi.utils.L
import com.yanzhenjie.permission.Action
import com.yanzhenjie.permission.AndPermission
import com.yanzhenjie.permission.runtime.Permission


abstract class BaseActivity : AppCompatActivity() {

    /** 获取布局id */
    abstract fun getLayoutId(): Int
    /** 获取标题 */
    abstract fun getTitleText(): String
    /** 是否显示返回键 */
    abstract fun isShowBack(): Boolean
    /** 初始化 */
    abstract fun initView()
    private val codeWindowPermission = 1000

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(getLayoutId())
        val isTrue = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP
        if(isTrue) {
            supportActionBar?.let {
                it.title = getTitleText()
                it.setDisplayHomeAsUpEnabled(isShowBack()) // 是否显示返回键
                it.elevation = 0f // 透明度
            }
        }
        initView()
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == android.R.id.home) {
            finish()
        }
        return true
    }

    // 检查窗口权限
    protected fun checkWindowPerission(): Boolean {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // >= 23  6.0
            return Settings.canDrawOverlays(this)
        }

        return true
    }

    // 申请权限
    protected fun requestWindowPermission(packageName: String) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // >= 23  6.0
            startActivityForResult(
                Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:$packageName")),
                codeWindowPermission)
        }

    }
   // 检查权限
    protected fun checkPermission(permission: String): Boolean {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // >= 23  6.0
            return (checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED)
        }
        return true
    }
    // 请求权限
    protected fun requestPermission(permisson: Array<String>, granted: Action<List<String>>) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // >= 23  6.0
            AndPermission.with(this).runtime().permission(permisson)
                .onGranted { granted }
                .start()
            }
    }

}
